# 闭包：动态的生成函数

# 例子1
def f_out(times):
    print('in f_out')

    # times在f_out函数中相对于f_in函数的外部变量
    def f_in(num):
        return times * num  # f_in可以调用外部变量times

    return f_in  # 函数f_in()的地址f_in返回给f_out()


f_10_times = f_out(10)
f_20_time = f_out(20)

# 给外部函数f_out传参后会先执行该函数内的所有语句
print(f_10_times(5))
print(f_20_time(5))


# 例子2
def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i * i

        fs.append(f)
    return fs


f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())


# 例子3
def count():
    def f(j):
        def g():
            return j * j

        return g

    fs = []
    for i in range(1, 4):
        fs.append(f(i))  # f(i)立刻被执行，因此i的当前值被传入f()
    return fs


f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
